package com.xiaoyyu;

import java.awt.image.RenderedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import org.opencv.highgui.HighGui;
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.MatOfRect;
import org.opencv.core.Point;
import org.opencv.core.Rect;
import org.opencv.core.Scalar;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
import org.opencv.objdetect.CascadeClassifier;


public class FaceDemoWithImage {

  static {
    //必须要写
    System.out.println("开始运行......");
    System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
    System.out.println("opencv\t"+Core.VERSION);
  }



  public static void main(String[] args) throws IOException {

    //图片地址
    String inputImagePath = "demo2.jpg";
    // 指定读出的图片路径和输出的文件
    String outputImageFile = "demo_identificate.jpg";
    File outputFile = new File(outputImageFile);

    //加载lib,这个lib的名称
    System.loadLibrary(Core.NATIVE_LIBRARY_NAME);

    //读取图像的 mat信息
    Mat image = Imgcodecs.imread(inputImagePath);;

    //初始化人脸识别类
    MatOfRect faceDetections = new MatOfRect();
    //添加识别模型
    CascadeClassifier faceDetector = new CascadeClassifier("D:\\Program\\opencv\\sources\\data\\haarcascades\\haarcascade_frontalface_alt.xml");
    //识别脸
    faceDetector.detectMultiScale(image, faceDetections);

    // 画出脸的位置
    for (Rect rect : faceDetections.toArray()) {
      Imgproc.rectangle(image, new Point(rect.x, rect.y), new Point(rect.x + rect.width, rect.y + rect.height), new Scalar(0, 0, 255), 2);
    }

    // 写入到文件
    ImageIO.write((RenderedImage) HighGui.toBufferedImage(image), "jpg", outputFile);

    System.out.print("图片已经识别");
  }

}
